package indi.zhifa.engine.core.excel.handler;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import indi.zhifa.engine.core.excel.entity.BaseExcelSheetRowData;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;

import java.lang.reflect.Field;


@Slf4j
public class StringCellHandler implements IExcelCellHandler {
    @Override
    public Object handle(Cell pCell,Class pClass) {
        if(null == pCell){
            return null;
        }
        String strVal = null;
        if(pCell.getCellType() == CellType.STRING){
            strVal = pCell.getStringCellValue().trim();
        } else if(pCell.getCellType() == CellType._NONE || pCell.getCellType() == CellType.BLANK){
            strVal = null;
        }else if(pCell.getCellType() == CellType.NUMERIC || pCell.getCellType() == CellType.FORMULA){
            double dCellValue = pCell.getNumericCellValue();
            dCellValue = Math.round(dCellValue * 1000000.0)/1000000.0;
            strVal = String.valueOf(dCellValue);
        }
        if(!StrUtil.isBlankIfStr(strVal)){
            strVal = null;
        }
        return strVal;
    }

    @Override
    public void fill(Cell pCell, BaseExcelSheetRowData pRowData, Field pField) throws IllegalAccessException {
        Object data = pField.get(pRowData);
        if(null != data){
            String sData = (String) data;
            if(null != sData){
                pCell.setCellValue(sData);
            }else{
                log.error("对象的字段 "+pField.getName()+" 不是字符串, \n"+ JSON.toJSONString(pRowData, JSONWriter.Feature.PrettyFormat));
            }
        }
    }
}
